package com.sanploy.manage.service.impl;


import com.sanploy.common.domain.Message;
import com.sanploy.common.domain.dto.MessageDto;
import com.sanploy.common.domain.dto.Pages;
import com.sanploy.common.domain.vo.Page;

import com.sanploy.manage.mapper.MessageMapper;
import com.sanploy.manage.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

/**
 * Created by zhu yingzhi on 2017/10/12.
 * @author yingzhi zhu
 * 消息逻辑处理接口实现类
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;


    /**
     * 轮询的消息服务
     */
    private volatile String socketMessage;

    @Override
    public Page<Message> getAllMessage(Pages mypages,boolean is_read) {
        Page<Message> page = new Page<>();
        int total = messageMapper.findMessageCount(is_read);
        page.setTotalPage((int)Math.ceil((double)total/(double)mypages.getPageSize()));
        page.setTotal(total);
        page.setCurrentPage(mypages.getCurrentPage());
        page.setPageSize(mypages.getPageSize());
        page.setList(messageMapper.getAllMessage((mypages.getCurrentPage()-1)*mypages.getPageSize(),mypages.getPageSize(),is_read));
        return page;
    }

    @Override
    public int countMessage(boolean is_read) {

        return messageMapper.findMessageCount(is_read);
    }

    /**
     * socket发送 暂时废弃
     * @param message 消息DTO
     * @return
     */
    @Override
    public int addMessage(MessageDto message) {
//        message.setAdd_time(CommonUtil.getTimeNormal());
//        sendMessage(message,"/messageSocket/chain/newMessage");

        //添加进发消息队列
        if (socketMessage==null){
            socketMessage = message.getMessage();
        }else {
            socketMessage = socketMessage+"\n"+message.getMessage();
        }
        return messageMapper.addMessage(message);
    }

    @Override
    public Message findById(Long id) {
        return messageMapper.findById(id);
    }

    @Override
    public int setIsReadMsg(String[] id_arr) {
        return messageMapper.setIsReadMsg(id_arr);
    }


    @Override
    public String newMessage() {
        //把消息队列中进行赋值
        String message = socketMessage;
        socketMessage = null;
        return message;
    }




}
